<template>
  <div class="mv-tabs">
    <div class="tabs" ref="tabsWrapper">
      <ul ref="tab">
        <li v-for="(item, index) in tabs" :key="index" @click="selectItem(index)">
          <div :class="['tab-item', {'link-active': index === currentIndex}]">
            <span class="tab-link">{{item.title}}</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

const NAV_WIDTH = 80
export default {
  name: 'mnav',
  props: {
    tabs: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      currentIndex: 0
    }
  },
  mounted () {
    this.$nextTick(() => {
      this._initMenu()
    })
  },
  methods: {
    selectItem (index) {
      let tabs = this.$refs.tab
      let moveX = +tabs.style.transform.replace(/[^0-9\-,]/g, '').split(',')[0]
      let _index = Math.floor(document.body.clientWidth / 2 / NAV_WIDTH)
      if (_index < index) {
        moveX = -(index - _index) * NAV_WIDTH
      } else {
        moveX = 0
      }
      tabs.style.transform = `translate(${moveX}px, 0) scale(1) translateZ(0px)`
      tabs.style.transitionDuration = `500ms`
      this.currentIndex = index
      this.$emit('navPageIndex', index)
    },
    _initMenu () {
      let width = this.tabs.length * NAV_WIDTH
      this.$refs.tab.style.width = `${width}px`
      this.$nextTick(() => {
        if (!this.scroll) {
          this.scroll = new BScroll(this.$refs.tabsWrapper, {
            scrollX: true,
            eventPassthrough: 'vertical'
          })
        } else {
          this.scroll.refresh()
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
  .mv-tabs
    position fixed
    // top -5.5rem
    top 0
    width 100%
    background-color #ffffff
    z-index 50
    .tabs
      height 40px
      width 100%
      line-height 40px
      box-sizing border-box
      overflow hidden
      white-space nowrap
      ul
        margin: 0
      .tab-item
        float left
        width 80px
        height 40px
        text-align center
        .tab-link
          padding-bottom 2px
          color #333333
        &.link-active
          color #d33a31
          border-bottom 2px solid #d33a31
          box-sizing border-box
</style>
